package cn.jn.lhm.netty.part08.chat.handler;

import cn.jn.lhm.netty.part08.chat.config.UserThread;
import cn.jn.lhm.netty.part08.chat.message.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/11/1 - 0:01
 **/
@Slf4j
public class ClientInitHandler extends SimpleChannelInboundHandler<LoginResponseMessage> {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof GroupCreateResponseMessage gcMsg) {
            log.info(UserThread.getUsername() + gcMsg.getReason());
        } else if (msg instanceof GroupChatResponseMessage gcMsg) {
            log.info("[{}]-[{}]: {}", gcMsg.getGroupName(), gcMsg.getFrom(), gcMsg.getContent());
        } else if (msg instanceof ChatResponseMessage gcMsg) {
            log.info("[{}]-[{}]", gcMsg.getFrom(), gcMsg.getContent());
        } else {
            log.info("收到服务端响应消息：{}", msg);
        }
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginResponseMessage responseMessage) throws Exception {
        if (responseMessage.isSuccess()) {
            System.out.println(responseMessage.getReason());
            initChatThread(ctx);
        } else {
            System.out.println(responseMessage.getReason());
            // 清理username
            // UserThread.clear();
            // 关闭客户端连接
            ctx.channel().close();
        }
    }

    private static void initChatThread(ChannelHandlerContext ctx) {
        String username = UserThread.getUsername();
        Thread thread = new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.println("==================================");
                System.out.println("send [username] [content]");
                System.out.println("gs [group name] [content]");
                System.out.println("gc [group name] [m1,m2,m3...]");
                System.out.println("gm [group name]");
                System.out.println("gj [group name]");
                System.out.println("gq [group name]");
                System.out.println("quit");
                System.out.println("==================================");
                String command = null;
                try {
                    command = scanner.nextLine();
                } catch (Exception e) {
                    break;
                }
                String[] s = command.split(" ");
                switch (s[0]) {
                    case "send":
                        ctx.writeAndFlush(new ChatRequestMessage(username, s[1], s[2]));
                        break;
                    case "gs":
                        ctx.writeAndFlush(new GroupChatRequestMessage(username, s[1], s[2]));
                        break;
                    case "gc":
                        Set<String> set = new HashSet<>(Arrays.asList(s[2].split(",")));
                        set.add(username); // 加入自己
                        ctx.writeAndFlush(new GroupCreateRequestMessage(s[1], set));
                        break;
                    case "gm":
                        ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                        break;
                    case "gj":
                        ctx.writeAndFlush(new GroupJoinRequestMessage(username, s[1]));
                        break;
                    case "gq":
                        ctx.writeAndFlush(new GroupQuitRequestMessage(username, s[1]));
                        break;
                    case "quit":
                        ctx.channel().close();
                        return;
                }
            }
        }, "system in");
        thread.setDaemon(true);
        thread.start();
    }
}
